<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 卡片头部 -->
            <div slot="header">
                <el-button type="primary" @click="addOrEditRoles(-1)">添加角色</el-button>
            </div>

            <!-- 卡片主体 -->
            <div>
                <el-table :data="rolesList">
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-row v-for="(item1, index1) in scope.row.children" :key="item1.id"
                                :class="['b_bottom', index1 === 0 ? 'b_top' : '', 'v_center']">
                                <!-- 一级权限 -->
                                <el-col :span="5">
                                    <el-tag closable @close="removeRightsById(scope.row, item1)">{{ item1.authName }}
                                    </el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="19">
                                    <el-row v-for="(item2, index2) in item1.children" :key="item2.id"
                                        :class="[index2 === 0 ? '' : 'b_top', 'v_center']">
                                        <!-- 二级权限 -->
                                        <el-col :span="6">
                                            <el-tag type="success" closable @close="removeRightsById(scope.row, item2)">
                                                {{ item2.authName }}
                                            </el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                        <!-- 三级权限 -->
                                        <el-col :span="18">
                                            <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id"
                                                closable @close="removeRightsById(scope.row, item3)">
                                                {{ item3.authName }}
                                            </el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>
                    <el-table-column prop="roleName" label="角色名称"></el-table-column>
                    <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" @click="addOrEditRoles(scope.row.id)">编辑</el-button>
                            <el-button slot="reference" size="mini" type="danger"
                                @click="deleteRoles(scope.row.id, scope.row.roleName)">
                                删除
                            </el-button>
                            <el-button size="mini" type="warning" @click="showSetRightsDialog(scope.row)">分配权限
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 添加/编辑角色对话框 -->
            <el-dialog :title="addOrEditRolesDialogTitle" :visible.sync="addOrEditRolesDialogVisible" width="30%"
                :close-on-click-modal="false" @close="addOrEditRolesDialogClose">
                <el-form :model="addOrEditRolesFormData" :rules="addOrEditRolesFormRules" ref="addOrEditRolesFormRef"
                    label-width="100px" status-icon>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addOrEditRolesFormData.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addOrEditRolesFormData.roleDesc">
                        </el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer">
                    <el-button @click="addOrEditRolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addOrEditRolesSubmit()">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 分配权限对话框 -->
            <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="30%" :close-on-click-modal="false"
                @close="setRightsDialogClose">
                <el-tree :data="rightsList" :props="defaultProps" node-key="id" default-expand-all show-checkbox
                    :default-checked-keys="threeLevelRightsId" ref="treeRef">
                </el-tree>
                <span slot="footer">
                    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="setRightsSubmit()">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 角色列表
            rolesList: [],
            // 添加/编辑角色对话框的标题
            addOrEditRolesDialogTitle: '',
            // 添加/编辑角色对话框的显示与隐藏
            addOrEditRolesDialogVisible: false,
            // 添加/编辑角色表单的数据绑定对象
            addOrEditRolesFormData: {
                roleName: '',
                roleDesc: ''
            },
            // 添加/编辑角色表单的验证规则对象
            addOrEditRolesFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 1, max: 11, message: '长度在1到11个字符' },
                    { pattern: /^[^\s]*$/, message: '禁止输入空格', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { pattern: /^[^\s]*$/, message: '禁止输入空格', trigger: 'blur' }
                ]
            },
            // 分配角色对话框的显示与隐藏
            setRightsDialogVisible: false,
            // 权限列表
            rightsList: [],
            // 树形控件的属性绑定对象
            defaultProps: {
                // 指定节点标签为节点对象的某个属性值
                label: 'authName',
                // 指定子树为节点对象的某个属性值
                children: 'children'
            },
            // 三级权限Id
            threeLevelRightsId: [],
            // 角色id
            roleId: ''
        }
    },
    created() {
        // 获取角色列表
        this.getRolesList();
    },
    methods: {
        // 获取角色列表
        async getRolesList() {
            const { data: res } = await this.$http.get('roles');
            if (res.meta.status !== 200) return this.$message.error('角色列表获取失败');
            this.rolesList = res.data;
        },
        // 控制添加/编辑角色对话框的显示与标题
        addOrEditRoles(id) {
            // 显示对话框
            this.addOrEditRolesDialogVisible = true;
            if (id > 0) {
                // 编辑角色
                this.addOrEditRolesDialogTitle = '编辑角色';
                // 回写编辑角色数据
                this.getEditRolesData(id);
            } else {
                // 添加角色
                this.addOrEditRolesDialogTitle = '添加角色';
                this.addOrEditRolesFormData = {};
            }
        },
        // 删除角色
        deleteRoles(roleId, roleName) {
            this.$confirm(`此操作将删除 ${roleName}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete('roles/' + roleId);
                if (res.meta.status !== 200) return this.$message.error('删除角色失败');
                this.$message({
                    type: 'success',
                    message: '删除角色成功!'
                });
                // 重新获取角色列表
                this.getRolesList();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 控制分配权限对话框的显示
        showSetRightsDialog(node) {
            // 显示对话框
            this.setRightsDialogVisible = true;
            // 获取所有权限列表
            this.getAllRightsList();
            // 回写三级权限数据
            this.getRightsData(node, this.threeLevelRightsId);
            // 将角色id存储到data数据中
            this.roleId = node.id;
        },
        // 展开列删除权限
        removeRightsById(roleInfo, rightInfo) {
            this.$confirm(`此操作将删除 ${rightInfo.authName} 权限, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`roles/${roleInfo.id}/rights/${rightInfo.id}`);
                if (res.meta.status !== 200) return this.$message.error('删除权限失败');
                this.$message({
                    type: 'success',
                    message: '删除权限成功!'
                });
                // 重新获取权限列表
                roleInfo.children = res.data;
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 添加/编辑角色对话框的关闭事件
        addOrEditRolesDialogClose() {
            // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
            this.$refs.addOrEditRolesFormRef.resetFields();
        },
        // 回写编辑角色数据
        async getEditRolesData(id) {
            const { data: res } = await this.$http.get('roles/' + id);
            if (res.meta.status !== 200) return this.$message.error('角色信息获取失败');
            this.addOrEditRolesFormData = res.data;
        },
        // 确认提交 添加/编辑角色
        addOrEditRolesSubmit() {
            // 对整个表单进行校验
            this.$refs.addOrEditRolesFormRef.validate(async valid => {
                if (valid) {
                    // 验证通过
                    if (this.addOrEditRolesFormData.roleId) {
                        // 编辑用户
                        const { data: res } = await this.$http.put('roles/' + this.addOrEditRolesFormData.roleId, this.addOrEditRolesFormData);
                        if (res.meta.status !== 200) return this.$message.error('角色信息更新失败');
                        this.$message.success('角色信息更新成功');
                    } else {
                        // 添加用户
                        const { data: res } = await this.$http.post('roles', this.addOrEditRolesFormData);
                        if (res.meta.status !== 201) return this.$message.error('添加角色失败');
                        this.$message.success('添加角色成功');
                    }
                    this.getRolesList();
                    this.addOrEditRolesDialogVisible = false;
                }
            });
        },
        // 获取所有权限列表
        async getAllRightsList() {
            const { data: res } = await this.$http.get('rights/tree');
            if (res.meta.status !== 200) return this.$message.error('权限列表数据获取失败');
            this.rightsList = res.data;
        },
        // 回写三级权限数据
        getRightsData(node, arr) {
            if (!node.children) {
                // 三级权限
                arr.push(node.id);
            } else {
                // 一级或二级权限
                node.children.forEach(element => {
                    this.getRightsData(element, arr);
                });
            }
        },
        // 监听分配权限对话框关闭事件
        setRightsDialogClose() {
            // 重置获取到的三级权限id
            this.threeLevelRightsId = [];
        },
        // 确定提交 权限
        async setRightsSubmit() {
            const checkKeys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const checkKeysStr = checkKeys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
                rids: checkKeysStr
            })
            if (res.meta.status !== 200) return this.$message.error('角色授权失败')
            this.$message.success('角色授权成功')
            this.getRolesList()
            this.setRightsDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.b_bottom {
    border-bottom: 1px solid #eee;
}

.b_top {
    border-top: 1px solid #eee;
}

.v_center {
    display: flex;
    align-items: center;
}
</style>
